﻿using System.Collections.Generic;
using System.Linq;
using SimpleQueryTool.Library;
using Caliburn.Micro;
using SimpleQueryTool.ViewModels.Connections;

namespace SimpleQueryTool.ViewModels
{
	public class ToolBarViewModel : Screen
	{
		private readonly IEventAggregator _eventAggregator;
		public List<ConnectionDetail> Connections { get; set; }

		public ToolBarViewModel(IEventAggregator eventAggregator)
		{
			_eventAggregator = eventAggregator;
			Connections = new List<ConnectionDetail>();

			var connection = new ConnectionDetail();
			connection.Name = "MyTestConnection";
			connection.Providername = "System.Data.SqlServerCe.3.5";
			connection.ConnectionString = @"Data Source=C:\Codeplex\SimpleQueryTool\Branches\Main\SimpleQueryTool.IntegrationTests\Database\TestDB.sdf;Password=whatever;Persist Security Info=False;";
			Connections.Add(connection);
			
			Connections.Add(new ConnectionDetail() { Name = "Test2" });
			Connections.Add(new ConnectionDetail() { Name = "Test3" });
			Connections.Add(new ConnectionDetail() { Name = "Test4" });
			Connections.Add(new ConnectionDetail() { Name = "Connection Manager..." });

			SelectedConnection = Connections.First();
		}

		private ConnectionDetail _selectedConnection;
		public ConnectionDetail SelectedConnection
		{
			get { return _selectedConnection; }
			set
			{ 
				_selectedConnection = value; 
				NotifyOfPropertyChange(() => SelectedConnection); 
			}
		}

		public void OpenConnectionManager()
		{
			if (SelectedConnection.Name == "Connection Manager...")
			{

				var window = new WindowManager();
				window.Show(new ConnectionManagerViewModel());
			}
		}

		public bool CanExecuteQuery { get { return SelectedConnection != null; } }
		
		public void ExecuteQuery()
		{
			var message = new ExecuteQueryMessage();
			message.Connection = SelectedConnection;
			_eventAggregator.Publish(message);
		}
	}
}